package com.baizhi.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtils {
    private static  SqlSessionFactory factory ;
    static {
        //1 读取配置文件
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        //2 创建SqlSessionFactory
        factory = new SqlSessionFactoryBuilder().build(in);
    }
    //抽取前3步，返回sqlSession
    public static SqlSession openSession(){
        //3 通过factory获取sqlSession
        SqlSession sqlSession  = factory.openSession();
        return sqlSession;
    }
    //抽取最后一步，释放资源
    public static void close(SqlSession sqlSession){
        if(sqlSession != null){
            sqlSession.close();
        }
    }

    public static void main(String[] args) {

        System.out.println(openSession());
    }
}
